from rest_framework.response import Response

from rest_framework import viewsets
from .models import Group, InterfacePath, FirstMenu


class UpdateAdminPermission(viewsets.ViewSet,
                            viewsets.mixins.CreateModelMixin,
                            ):
    def create(self, request, *args, **kwargs):
        ## 1、拿到管理员组对象
        groupobj = Group.objects.filter(title="管理员").first()
        # print("111", groupobj, type(groupobj))
        if not groupobj:
            return Response({"msg": '未找到"管理员"组，请检查用户组；'})

        ## 2、获取管理员组已经关联的接口权限id
        existing_group_ids = set(groupobj.interfacepaths.values_list('id', flat=True))
        ## 已关联的菜单权限
        existing_menu_ids = set(groupobj.menus.values_list('id', flat=True))

        ## 3、获取所有的接口权限
        existing_interface_ids = InterfacePath.objects.values_list('id', flat=True)
        ## 所有菜单
        existing_menu_all_ids = FirstMenu.objects.values_list('id', flat=True)

        ## 4、用所有接口权限减去已经关联的接口权限
        new_group_ids = set(existing_interface_ids) - existing_group_ids
        new_menu_ids = set(existing_menu_all_ids) - existing_menu_ids

        ## 5、获取需要新增的接口权限实例对象
        new_interfaces = InterfacePath.objects.filter(id__in=new_group_ids)
        ## 获取需要新增的菜单对象
        new_menus = FirstMenu.objects.filter(id__in=new_menu_ids)

        ## 6、将接口权限更新给管理员组
        try:
            groupobj.interfacepaths.add(*new_interfaces)
            groupobj.menus.add(*new_menus)
        except Exception as e:
            return Response({"msg": f"管理组权限已经更新失败：{e}"})

        return Response({"msg": "管理组权限已经更新成功"})
